package ar.edu.unrn.lia.security;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import ar.edu.unrn.lia.seguridad.AuthenticationService;
import ar.edu.unrn.lia.service.UserService;

@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6262643531993499317L;

	private String username;

	private String password;

	private String nombre;

	public String getNombre() {
		return nombre;
	}

	public void setNombre(String nombre) {
		this.nombre = nombre;
	}

	@ManagedProperty(value = "#{authenticationService}")
	AuthenticationService authenticationService;

	@ManagedProperty(value = "#{userService}")
	UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public AuthenticationService getAuthenticationService() {
		return authenticationService;
	}

	public void setAuthenticationService(
			AuthenticationService authenticationService) {
		this.authenticationService = authenticationService;
	}

	public String login() {
		try {

			// check if userdata is given
			if (this.getUsername() == null || this.getPassword() == null) {
				FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, 
						"Fallo en la Autenticación", 
						"Usuaio y/o Clave incorrentos.");
				FacesContext.getCurrentInstance().addMessage(null, facesMsg);
				return null;
			}

			if (authenticationService.login(username, password)) 
			{
				setNombre(getUserService().getEntityById(1L).getFirstName());
				return "/home?faces-redirect=true";
			}

		} catch (UsernameNotFoundException e) {
			FacesMessage facesMsg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Fallo en la Autenticación", 
					"Usuaio y/o Clave incorrentos.");
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);

		} catch (AuthenticationException e) {
			FacesMessage facesMsg = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Fallo en la Autenticación", 
					"Usuaio y/o Clave incorrentos.");
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);

		}

		return null;
	}

	public void logout() {

		authenticationService.logout();

	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
